package com.lexed.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class Database {

	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/hr";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "ok";
	
	private static Connection connection;
	
	private static Map<String,PreparedStatement> preparedStatements = 
			new HashMap<String,PreparedStatement>();
	
	public static Connection getConnection() throws Exception{
		if(connection == null){
			// 1\加载驱动类
			Class.forName(DRIVER);
			
			// 2\创建连接
			connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		}
		
		return connection;
	}
	
	public static PreparedStatement getStatement(String sql , Object ... arg) throws Exception{
		
		PreparedStatement preparedStatement = preparedStatements.get(sql);
		if(preparedStatement == null){
			preparedStatement = getConnection().prepareStatement(sql);
			preparedStatements.put(sql, preparedStatement);
		}
		
		if(arg != null) {
			
			for(int i=0; i<arg.length; i++){
				Object obj =  arg[i];
				preparedStatement.setObject(i+1, obj);
			}
			
		}
		
		return preparedStatement;	
	}
	
	public static void close(Connection connection, Statement statement, ResultSet resultSet){
		try {
			if(connection != null){
				connection.close();
			}
			if(statement != null){
				statement.close();
			}
			if(resultSet != null){
				resultSet.close();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
}
